

const app = getApp();
Page({
  data: {
    morechack: [],
    showmsg: false,
    showanswer: false,
    banners: [
      {
        ids: 1,
        imageUrl: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/banner1x.png',
        linkUrl: '/service/donation/donation'
      },
      {
        ids: 2,
        imageUrl: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/banner3x.png',
        linkUrl: '/service/activity/activity'
      }, {
        ids: 3,
        imageUrl: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/banner2x.png',
        linkUrl: ''
      }
    ],
    // 所有问题
    allQuestions: [],
    showJiucuoModal: "",//纠错弹窗
    showDatikaModal: false, // 答题卡弹窗显示状态
    answerCardDetail: null, // 答题卡详情数据
    questionId: "",
    // 显示的问题
    questions: [],//虚拟列表
    currentIndex: 0,
    showswiper: true,
    // 当前显示的问题序号
    currentShowSortNum: -1,
    list: [],
    // 总问题数
    totalQuestions: 0,
  },
  async onLoad(options) {
    const answerCardId = options.answerCardId;
    const isValidAnswerCardId = answerCardId && !isNaN(parseInt(answerCardId)) && parseInt(answerCardId) > 0;

    this.setData({
      questionId: 0, // 初始化为0，后续从答题卡数据中获取
      answerCardId: isValidAnswerCardId ? parseInt(answerCardId) : '', // 答题卡ID，只接受有效数字
    })
    await this.requestData()

    // 如果初始化能搞到上次停留的问题序号，就跳转过去
    // const lastQuestionSortNum = 255;

    this.goToQuestion(1);

  },

  async requestData() {
    const params = {
      page: 1,
      pageSize: 1000,
      subjectId: this.data.subjectId,
      chapterId: this.data.chapterId
    };

    const res = await app.api.getErrorBookList(params)
    res.data.records = []
    // 处理用户答案映射
    const recordsMap = {};
    res.data.records.forEach(item => {
      if (item.user_answer) {
        recordsMap[item.question_id] = item.user_answer;
      }
    });


    // 处理题目数据
    const list = res.data.questions.map((item, index) => {
      const question = JSON.parse(JSON.stringify(item));

      // 设置用户答案
      question.user_answer = recordsMap[question.id] || null;
      question.showanswer = false
      if (question.user_answer) {
        question.showanswer = true
      }
      // 处理题目内容
      question.question_name = this.parseMarkdown(question.question_name);
      question.right_key = this.parseMarkdown(question.right_key);
      question.questionid = question.id;
      question.sort = index + 1;
      question.id = question.sort;

      // 初始化答题状态
      question.selectedAnswerId = "";
      question.selectedOption = null;
      question.selectedOptions = [];
      question.isAnswered = false;
      question.isCorrect = false;
      question.userAnswer = null;
      question.selectedClass = [];

      // 处理选择题选项
      if ([0, 1, 3].includes(question.question_type) && question.content) {
        try {
          const parsed = question.content;
          if (parsed?.options) {
            question.theoptions = parsed.options.map(option => {

              const isSelected = question.question_type === 0
                ? question.user_answer === option.key
                : question.user_answer?.includes(option.key);

              return {
                ...option,
                selectmore: !!isSelected,
                content: this.parseMarkdown(option.content)
              };
            });
          }
        } catch {
          question.theoptions = [];
        }
      }
      if (question.question_type == 3) {
        question.theoptions = ['正确', '错误']
      }
      return question;
    });

    // 一次性设置数据
    this.setData({
      list,
      totalQuestions: list.length,
      allQuestions: list,
      questionId: list[0]?.questionid || ''
    });
  },
  showAnswerDetail() {
    const theindex = this.data.questions.findIndex(item => item.questionid === this.data.questionId);
    const theindex2 = this.data.allQuestions.findIndex(item => item.questionid === this.data.questionId);
    this.setData({
      [`questions[${theindex}].showanswer`]: true,
      [`allQuestions[${theindex2}].showanswer`]: true,
    })

  },
  // 打开答题卡弹窗
  openDatikaModal: function () {
    // 如果有答题卡ID，先加载答题卡详情数据
    if (this.data.answerCardId) {
      this.loadAnswerCardDetail().then(() => {
        // 数据加载完成后显示弹窗
        this.setData({
          showDatikaModal: true
        });

        // 强制更新答题卡组件数据，确保组件接收到最新数据
        setTimeout(() => {
          // 通过设置相同的值来触发observers监听
          this.setData({
            answerRecords: [...this.data.allQuestions]
          });
        }, 100);
      }).catch(err => {
        console.error('加载答题卡详情失败:', err);
        // 即使加载失败也显示弹窗，但使用默认数据
        this.setData({
          showDatikaModal: true,
          answerRecords: this.data.allQuestions || []
        });
      });
    } else {
      // 如果没有答题卡ID，直接显示弹窗
      this.setData({
        showDatikaModal: true,
        answerRecords: this.data.allQuestions || []
      });
    }
  },

  // 关闭答题卡弹窗
  closeDatikaModal: function () {
    this.setData({
      showDatikaModal: false
    });
  },

  // 加载答题卡详情
  loadAnswerCardDetail: function () {
    return new Promise((resolve, reject) => {
      if (!this.data.answerCardId) {
        reject(new Error('没有答题卡ID'));
        return;
      }
      const params = {
        page: 1,
        pageSize: 1000,
        subjectId: this.data.subjectId,
        chapterId: this.data.chapterId
      };
      app.api.getAnswerCardDetail({
        answerCardId: this.data.answerCardId
      }).then(res => {
        if (res && res.data) {
          this.setData({
            answerCardDetail: res.data,
            answerRecords: this.data.allQuestions || []
          });
          resolve(res.data);
        } else {
          reject(new Error('返回数据格式不正确'));
        }
      }).catch(err => {
        console.error('获取答题卡详情失败:', err);
        reject(err);
      });
    });
  },
  async getpinglun() {
    let pinglunres = await app.api.getCommentList({
      questionId: this.data.questionId,
      page: 1,
      limit: 100
    })
    const commentData = pinglunres.data;

    // 格式化评论数据
    const formattedComments = commentData.data.map(comment => ({
      id: comment.id,
      content: comment.content,
      likeCount: comment.like_count || 0,
      createTime: this.formatTime(comment.created_at),
      user: comment.user || {
        id: 0,
        nickname: '匿名用户',
        avatar: 'https://exam-1304576422.cos.ap-guangzhou.myqcloud.com/static/default_avatar.png'
      }
    }));

    let array1 = this.data.questions.map((item, index) => {
      if (item.questionid == this.data.questionId) {
        item.commentList = formattedComments
      }
      return item
    })
    let array2 = this.data.allQuestions.map((item, index) => {
      if (item.questionid == this.data.questionId) {
        item.commentList = formattedComments
      }
      return item
    })


    this.setData({
      questions: array1,//虚拟列表的
      allQuestions: array2,
    })
  },

  /**
   * 标记已做（非选择题）
   */
  markAsDone: async function (e) {
    try {
      const userAnswer = '已标记已做';
      const isCorrect = true; // 非选择题默认标记为已查看状态

      // 如果有答题卡ID，提交记录到服务器
      if (this.data.answerCardId) {
        await app.api.submitAnswer({
          cardId: this.data.answerCardId,
          questionId: this.data.questionId,
          userAnswer: ".",
          answerTime: new Date().toISOString()
        });
      }
      this.setData({
        questionId: this.data.allQuestions[e.currentTarget.dataset.istrue.sort - 1].questionid
      })
      this.getpinglun()
      let theindex
      this.data.questions.map((items, indexs) => {
        if (items.questionid == this.data.questionId) {
          theindex = indexs
        }
      })
      question.showanswer = true
      this.setData({
        // 更新虚拟列表中的当前问题
        [`questions[${theindex}].user_answer`]: '-',
        [`questions[${theindex}].showanswer`]: true,
        // 更新全部问题列表中的对应问题
        [`allQuestions[${e.currentTarget.dataset.istrue.sort - 1}].user_answer`]: '-',
        [`allQuestions[${e.currentTarget.dataset.istrue.sort - 1}].showanswer`]: true
      }, () => {
      })

    } catch (error) {
      // wx.showToast({
      //   title: '标记失败，请重试',
      //   icon: 'none'
      // });
    } finally {
      // wx.hideLoading();
    }
  },

  sendMessage: function (e) {
    const jiexi = e.currentTarget.dataset.jiexi || '';
    if (!jiexi) {
      wx.showToast({
        title: '题目信息加载中',
        icon: 'none'
      });
      return;
    }

    const message = "解析下这个题目：" + jiexi;

    // 重置消息列表，只保留当前解析
    this.setData({
      messages: []
    });

    this.setData({
      isLoading: true,
      inputValue: ''
    });

    // 添加用户消息
    const userMessage = {
      type: 'user',
      content: message,
      time: this.formatTime(new Date())
    };

    this.setData({
      messages: [...this.data.messages, userMessage]
    }, () => {
      // 滚动到底部显示用户消息
      this.scrollToBottom();


    });

    // 调用AI问答接口
    this.callAIChat(message);
  },
  /**
 * 滚动到底部
 */
  scrollToBottom: function () {
    wx.createSelectorQuery().select('.ulss').boundingClientRect((rect) => {
      if (rect) {
        wx.createSelectorQuery().select('.ulss').scrollOffset((res) => {
          wx.createSelectorQuery().select('.ulss').context((context) => {
            context.context.scrollTo({
              scrollTop: res.scrollTop + rect.height + 100,
              duration: 300
            });
          }).exec();
        }).exec();
      }
    }).exec();
  },
  /**
 * 调用AI问答接口
 */

  /**
 * 滚动到底部
 */
  scrollToBottom: function () {
    wx.createSelectorQuery().select('.ulss').boundingClientRect((rect) => {
      if (rect) {
        wx.createSelectorQuery().select('.ulss').scrollOffset((res) => {
          wx.createSelectorQuery().select('.ulss').context((context) => {
            context.context.scrollTo({
              scrollTop: res.scrollTop + rect.height + 100,
              duration: 300
            });
          }).exec();
        }).exec();
      }
    }).exec();
  },
  callAIChat: function (message) {
    const that = this;

    // 创建AI消息对象（用于流式传输）- 直接显示"正在思考中..."
    const aiMessage = {
      type: 'ai',
      content: '正在思考中...',
      parsedContent: '正在思考中...',
      time: that.formatTime(new Date()),
      isStreaming: true // 标记为流式传输中
    };

    // 先将AI消息添加到消息列表
    that.setData({
      messages: [...that.data.messages, aiMessage]
    }, () => {
      // 滚动到底部
      that.scrollToBottom();
    });

    const app = getApp();
    wx.request({
      url: app.globalData.baseUrl + '/frontend/ai/chat',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('userToken') || ''
      },
      timeout: 60000, // 设置60秒超时时间
      data: {
        message: message,
        questionId: this.data.questionId,
        isFirstQuestion: this.data.isFirstQuestion ? 1 : 0,
        stream: 1 // 启用流式传输
      },
      success: function (res) {
        if (res.data.code === 200) {
          // 模拟流式效果：逐字显示内容
          const fullContent = res.data.data.content || '';
          const messages = that.data.messages;
          const lastIndex = messages.length - 1;

          // 延迟一小段时间后开始显示真实内容（让用户看到"正在思考中..."）
          setTimeout(() => {
            // 模拟逐字显示效果
            let currentIndex = 0;
            const typingInterval = setInterval(() => {
              if (currentIndex < fullContent.length) {
                const currentContent = fullContent.substring(0, currentIndex + 1);
                console.log(currentContent)
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  content: currentContent,
                  parsedContent: that.cleanAIMathText(that.parseMarkdown(currentContent))
                };

                that.setData({
                  messages: messages
                }, () => {
                  that.scrollToBottom();
                });

                currentIndex++;
              } else {
                clearInterval(typingInterval);

                // 流式传输完成
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  isStreaming: false
                };

                that.setData({
                  messages: messages,
                  isLoading: false,
                  isFirstQuestion: false
                }, () => {

                });
              }
            }, 30); // 每30ms显示一个字符
          }, 500);
        } else {
          // 处理错误情况
          const messages = that.data.messages;
          messages[messages.length - 1] = {
            ...messages[messages.length - 1],
            content: res.data.message || '服务器错误，请稍后重试',
            parsedContent: res.data.message || '服务器错误，请稍后重试',
            isStreaming: false
          };

          that.setData({
            messages: messages,
            isLoading: false
          });
        }
      },
      fail: function (error) {
        console.error('AI聊天请求失败:', error);

        const messages = that.data.messages;
        messages[messages.length - 1] = {
          ...messages[messages.length - 1],
          content: '网络错误，请检查网络连接后重试',
          parsedContent: '网络错误，请检查网络连接后重试',
          isStreaming: false
        };

        that.setData({
          messages: messages,
          isLoading: false
        });
      }
    });
  },

  /**
 * 增强版：处理包含数学公式的AI回复
 */
  cleanAIMathText: function (content) {
    if (!content) return ''

    let cleaned = content

    // 处理常见的数学环境
    cleaned = cleaned
      .replace(/\\begin\{equation\}([\s\S]*?)\\end\{equation\}/g, '$1')
      .replace(/\\begin\{align\}([\s\S]*?)\\end\{align\}/g, '$1')
      .replace(/\\begin\{array\}([\s\S]*?)\\end\{array\}/g, '$1')

      // 处理矩阵和数组
      .replace(/\\begin\{pmatrix\}([\s\S]*?)\\end\{pmatrix\}/g, '[$1]')
      .replace(/\\\\/g, ', ')  // 矩阵换行转逗号

    return this.cleanAIText(cleaned)
  },
  cleanAIText(content) {
    if (!content || typeof content !== 'string') return ''

    return content
      // 1. 先处理数学符号和希腊字母
      .replace(/\\pi/g, 'π')
      .replace(/\\alpha/g, 'α')
      .replace(/\\beta/g, 'β')
      .replace(/\\gamma/g, 'γ')
      .replace(/\\delta/g, 'δ')
      .replace(/\\epsilon/g, 'ε')
      .replace(/\\theta/g, 'θ')
      .replace(/\\lambda/g, 'λ')
      .replace(/\\mu/g, 'μ')
      .replace(/\\sigma/g, 'σ')
      .replace(/\\phi/g, 'φ')
      .replace(/\\omega/g, 'ω')
      .replace(/\\Omega/g, 'Ω')

      // 2. 处理常见的转义字符
      .replace(/\\,/g, ' ')           // 小空格
      .replace(/\\ /g, ' ')           // 空格
      .replace(/\\\(/g, '(')          // 左括号
      .replace(/\\\)/g, ')')          // 右括号
      .replace(/\\\[/g, '[')          // 左方括号
      .replace(/\\\]/g, ']')          // 右方括号
      .replace(/\\\{/g, '{')          // 左花括号
      .replace(/\\\}/g, '}')          // 右花括号

      // 3. 处理LaTeX命令
      .replace(/\\text\{/g, '')
      .replace(/\\text\{([^}]*)\}/g, '$1')  // 提取text内容
      .replace(/\\text\s*\{/g, '')
      .replace(/\\mathrm\{([^}]*)\}/g, '$1')
      .replace(/\\mathbf\{([^}]*)\}/g, '$1')

      // 4. 处理空格和间距命令
      .replace(/\\quad/g, '    ')
      .replace(/\\qquad/g, '        ')
      .replace(/\\! /g, '')
      .replace(/\\;/g, ' ')
      .replace(/\\:/g, ' ')

      // 5. 处理分数和根号（简化处理）
      .replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '($1)/($2)')
      .replace(/\\sqrt\{([^}]+)\}/g, '√$1')
      .replace(/\\sqrt\[([^\]]+)\]\{([^}]+)\}/g, '$1√$2')

      // 6. 处理上下标
      .replace(/\^\{([^}]+)\}/g, '^$1')
      .replace(/_\{([^}]+)\}/g, '_$1')

      // 7. 清理多余的斜杠（保留真正的转义字符）
      .replace(/\\([^a-zA-Z])/g, '$1')  // 非字母前的斜杠
      .replace(/\\$/g, '')              // 行末斜杠

      // 8. 清理多余的空格
      .replace(/\s+/g, ' ')
      .replace(/\n\s*\n/g, '\n\n')      // 保留段落空行
      .trim()

  },
  handlePinglunSubmit() {
    this.getpinglun()
  },


  /**
 * 格式化时间
 */
  formatTime: function (date) {
    if (!date) return '';

    // 如果是时间戳或字符串，转换为Date对象
    if (typeof date === 'number' || typeof date === 'string') {
      date = new Date(date);
    }

    // 检查是否为有效的Date对象
    if (!(date instanceof Date) || isNaN(date.getTime())) {
      return '';
    }

    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  /**
   * 简单的Markdown解析函数 - 处理标题、加粗、换行和图片
   */
  parseMarkdown: function (text) {
    if (!text) return '';

    let parsed = text;

    // 将 ### 标题 转换为 <h3>标题</h3>
    parsed = parsed.replace(/###\s+(.*?)(?=\n|$)/g, '<h3>$1</h3>');

    // 将 **文本** 转换为 <strong style="color: #9b1e23;">文本</strong>
    parsed = parsed.replace(/\*\*(.*?)\*\*/g, '<strong style="color: #9b1e23;">$1</strong>');

    // 将 \n 转换为 <br/>
    parsed = parsed.replace(/\n/g, '<br/>');




    // 为图片标签添加样式，确保100%显示
    parsed = parsed.replace(/<img([^>]+)>/g, '<img$1  mode="widthFix" style="max-width: 100%;display:black; height: auto;" />');

    // 处理Markdown格式的图片 ![alt](url)
    parsed = parsed.replace(/!\[(.*?)\]\((.*?)\)/g, '<img mode="widthFix" src="$2" alt="$1" style="max-width: 100%;display:black; height: auto;" />');

    return parsed;
  },
  onSwiperChange(e) {
    const { current } = e.detail;
    this.setData({ questionId: this.data.questions[current].questionid })

    const originData = JSON.parse(JSON.stringify(this.data.questions));
    const currentQuestion = originData[current];

    // 会引起数据变化
    this.goToQuestion(currentQuestion.id);
  },
  // 打开评论弹窗
  openPinglunModal: function () {
    const currentQuestionId = this.data.questionId || this.data.currentQuestionId;
    const currentBigitemId = this.data.currentQuestion ? this.data.currentQuestion.id : null;
    // 修复语法错误：移除无效的属性定义

    this.setData({
      showPinglunModal: true
    });
  },

  /**
   * 跳转上一题
   */
  goToPreviousQuestion() {
    const currentShowSortNum = this.data.currentShowSortNum;
    this.goToQuestion(this.fixSortNum(currentShowSortNum - 1));
  },

  /**
   * 跳转下一题
   */
  goToNextQuestion() {
    const currentShowSortNum = this.data.currentShowSortNum;
    this.goToQuestion(this.fixSortNum(currentShowSortNum + 1));
  },

  /**
   * 获取题目类型代码
   */
  getQuestionTypeCode: function (question) {
    const questionTypeValue = question.question_type;
    if (typeof questionTypeValue === 'number') {
      return questionTypeValue;
    } else if (typeof questionTypeValue === 'string') {
      switch (questionTypeValue) {
        case 'single_choice': return 0; break;
        case 'multiple_choice': return 1; break;
        case 'essay': return 4; break;
        default: return 0;
      }
    }
    return 0;
  },

  /**
   * 处理选项数据
   */
  processOptions: function (question) {
    let options = [];
    try {
      if (question.content) {
        const contentObj = JSON.parse(question.content);
        if (contentObj.options && Array.isArray(contentObj.options)) {
          options = contentObj.options;
        }
      }
    } catch (e) {
    }

    if (options.length === 0 && question.theoptions) {
      options = question.theoptions;
    }

    // 对于判断题，设置固定的"对"和"错"选项
    if (this.getQuestionTypeCode(question) === 3) {
      options = [
        { key: '0', content: '正确' },
        { key: '1', content: '错误' }
      ];
    }

    return options;
  },

  /**
   * 更新选项选中状态数组
   */
  updateSelectedClass: function (selectedOption, selectedOptions, userAnswer, isAnswered, questionTypeCode, options) {
    const optionsCount = options ? options.length : 0;
    const selectedClass = [];

    // 优先使用用户答案
    if (userAnswer && isAnswered) {
      for (let i = 0; i < optionsCount; i++) {
        const optionKey = String.fromCharCode(65 + i); // A, B, C, D...

        if (questionTypeCode === 0) {
          // 单选题：用户答案等于选项key
          selectedClass.push(userAnswer === optionKey ? 'selected' : '');
        } else if (questionTypeCode === 1) {
          // 多选题：用户答案包含选项key
          selectedClass.push(userAnswer.includes(optionKey) ? 'selected' : '');
        } else if (questionTypeCode === 3) {
          // 判断题：用户答案是"正确"或"错误"
          const booleanMapping = { 0: '正确', 1: '错误' };
          selectedClass.push(userAnswer === booleanMapping[i] ? 'selected' : '');
        } else {
          selectedClass.push('');
        }
      }
    } else {
      // 没有用户答案时使用当前选中状态
      for (let i = 0; i < optionsCount; i++) {
        if (questionTypeCode === 0 || questionTypeCode === 3) {
          // 单选题和判断题逻辑相同
          selectedClass.push(i === selectedOption ? 'selected' : '');
        } else if (questionTypeCode === 1) {
          // 多选题逻辑
          selectedClass.push(selectedOptions && selectedOptions.indexOf(i) > -1 ? 'selected' : '');
        } else {
          selectedClass.push('');
        }
      }
    }

    return selectedClass;
  },

  /**
   * 判断答案是否正确
   */
  isAnswerCorrect: function (question, userAnswer) {
    const questionTypeCode = this.getQuestionTypeCode(question);
    const correctAnswer = question.right_key || '';

    // 仅单选题、多选题、判断题检查正确性
    const checkableTypes = [0, 1, 3];
    if (!checkableTypes.includes(questionTypeCode)) {
      return true;
    }

    if (questionTypeCode === 0 || questionTypeCode === 3) {
      // 单选题和判断题：直接比较
      return userAnswer === correctAnswer;
    } else if (questionTypeCode === 1) {
      // 多选题：检查是否完全匹配（顺序无关）
      if (!userAnswer || !correctAnswer) return false;
      const userAnswers = userAnswer.split('');
      const correctAnswers = correctAnswer.split('');
      return userAnswers.sort().join('') === correctAnswers.sort().join('');
    }

    return false;
  },
  onAdBannerChange() { },
  // 单选题多选题 额外处理
  async onOptionTapmore(e) {
    const { dataset } = e.currentTarget;
    const { istrue, index } = dataset;

    // 更高效的方式查找索引
    const theindex = this.data.questions.findIndex(item => item.sort === istrue.sort);

    if (theindex === -1) return; // 找不到索引时直接返回
    if (this.data.questions[theindex].user_answer) {
      console.log("已答过了")
      return
    }
    // 获取当前状态
    const currentSelectMore = !this.data.questions[theindex].theoptions[index].selectmore;

    this.setData({
      // 更新虚拟列表中的当前问题
      [`questions[${theindex}].theoptions[${index}].selectmore`]: currentSelectMore,
      // 更新全部问题列表中的对应问题
      [`allQuestions[${istrue.sort - 1}].theoptions[${index}].selectmore`]: currentSelectMore
    });
    const question = this.data.allQuestions[e.currentTarget.dataset.istrue.sort - 1];
    if (question.question_type == 0) {
      await this.submitAnswer()

      if (question.theoptions[e.currentTarget.dataset.index].key == question.right_key) {
        console.log("答对了")
        this.goToQuestion(e.currentTarget.dataset.istrue.sort + 1);
        return
      } else {
        console.log("答错了")
        // 加入错题库
        console.log(question.theoptions[e.currentTarget.dataset.index])

      }
      // // 获取选项的key值
      // userAnswerValue = question.theoptions[e.currentTarget.dataset.index].key;
    }
  },
  /**
   * 处理选项点击事件
   */
  async onOptionTap(e) {
    const { dataset } = e.currentTarget;
    const { istrue, index } = dataset;

    if (this.data.allQuestions[e.currentTarget.dataset.istrue.sort - 1].user_answer) {
      console.log("已经答题过了")
      return
    }


    console.log(e.currentTarget.dataset)
    const { questionType, questionIndex, optionIndex } = e.currentTarget.dataset.istrue;
    const question = this.data.allQuestions[e.currentTarget.dataset.istrue.sort - 1];

    let userAnswerValue = ""
    // 0: 单选题  1:多选题 3:判断题 2:填空题 5:名词解释提  4:问答题 6: 论述题
    if (question.question_type == 0) {
      if (question.theoptions[e.currentTarget.dataset.index].key == question.right_key) {
        console.log("答对了")
        setTimeout(() => {
          this.goToQuestion(e.currentTarget.dataset.istrue.sort + 1);
        }, 200);
        return
      } else {
        console.log("答错了")
        // 加入错题库
        console.log(question.theoptions[e.currentTarget.dataset.index])

      }

      // 获取选项的key值
      userAnswerValue = question.theoptions[e.currentTarget.dataset.index].key;
    }
    // 判断题
    else if (question.question_type == 3) {
      let strings = ""
      if (e.currentTarget.dataset.index == 0) {
        strings = "正确"
      } if (e.currentTarget.dataset.index != 0) {
        strings = "错误"
      }
      if (strings == question.right_key) {
        console.log("答对了")
        // this.goToQuestion(e.currentTarget.dataset.istrue.sort + 1);
        // return
      } else {
        console.log("答错了")
        // 加入错题库
        console.log(e.currentTarget.dataset)
        console.log(question)
        console.log(question.theoptions[e.currentTarget.dataset.index])

      }
      userAnswerValue = strings
    }
    const theindex = this.data.questions.findIndex(item => item.sort === istrue.sort);

    this.getpinglun()
    this.setData({
      // 更新虚拟列表中的当前问题
      [`questions[${theindex}].user_answer`]: userAnswerValue,
      [`questions[${theindex}].showanswer`]: true,
      // 更新全部问题列表中的对应问题
      [`allQuestions[${e.currentTarget.dataset.istrue.sort - 1}].user_answer`]: userAnswerValue,
      [`allQuestions[${e.currentTarget.dataset.istrue.sort - 1}].showanswer`]: true
    })
    await app.api.submitAnswer({
      cardId: this.data.answerCardId,
      questionId: this.data.questionId,
      userAnswer: userAnswerValue,
      answerTime: new Date().toISOString()
    });

    // console.log(22222222222222222222)
    // console.log(question)
    // console.log(question.right_key)

    // 添加延迟以确保视图更新完成后再打印
    setTimeout(() => {
      console.log('数据更新后:', this.data.questions);
      console.log('全部问题更新后:', this.data.allQuestions);
    }, 100);



  },
  // 多选题提交答案
  async submitAnswer() {
    let chackstring = ""
    console.log(chackstring)
    let array = this.data.questions.map(item => {
      item.theoptions = item.theoptions && item.theoptions.map(itemzi => {
        if (this.data.questionId == item.questionid && itemzi.selectmore == true) {
          if (item.question_type == 1) {
            chackstring = chackstring + itemzi.key
          } else {
            chackstring = itemzi.key
          }

        }
        return itemzi
      })
      if (item.selectmore == true) {
        chackstring = chackstring + item.key
      }
      return item
    })
    console.log(chackstring)
    if (chackstring == "") {
      this.setData({
        showmsg: true,
        massges: "请选择选项",
      });
      setTimeout(() => {
        this.setData({
          showmsg: false,
          massges: "请选择选项",
        });
      }, 1000);
      return
    }
    if (this.data.answerCardId) {
      await app.api.submitAnswer({
        cardId: this.data.answerCardId,
        questionId: this.data.questionId,
        userAnswer: chackstring,
        answerTime: new Date().toISOString()
      });
    }
    this.getpinglun()
    const theindex = this.data.questions.findIndex(item => item.questionid === this.data.questionId);
    const theindex2 = this.data.allQuestions.findIndex(item => item.questionid === this.data.questionId);
    if (this.data.questions[theindex].right_key == chackstring) {
      console.log("答对了")
    } else {

      console.log("答错了")
    }
    this.setData({
      // 更新虚拟列表中的当前问题
      [`questions[${theindex}].user_answer`]: chackstring,
      [`questions[${theindex}].showanswer`]: true,
      // 更新全部问题列表中的对应问题
      [`allQuestions[${theindex2}].user_answer`]: chackstring,
      [`allQuestions[${theindex2}].showanswer`]: true,
    })
    this.processQuestions()
  },
  processQuestions() {

    // 处理 questions

    const questions = this.data.questions.map((question, index) => ({
      ...question,
      theoptions: question.theoptions && question.theoptions.map(option => ({
        ...option,
        isCorrect: question.right_key.includes(option.key)
      }))
    }));
    let allQuestions = this.data.allQuestions.map(item => {
      this.data.questions.map(itemzi => {
        if (item.questionid == itemzi.questionid) {
          if (item.theoptions) {
            item.theoptions = itemzi.theoptions
          }
        }
        return itemzi
      })
      return item
    })
    // let array= this.data.matchedQuestion
    // this.data.questions.map(item=>{
    //   item.theoptions
    //   array.map(item => {

    //   })
    // })
    // 更新 allQuestions
    // const allQuestions = this.data.allQuestions.map(question => {
    //   const matchedQuestion = questions.find(q => q.sort === question.sort);
    //   if (matchedQuestion) {
    //     return {
    //       ...question,
    //       theoptions: matchedQuestion.theoptions
    //     };
    //   }
    //   return question;
    // });

    this.setData({ questions, allQuestions });
  },
  clearthis: function () {
    this.setData({
      types: "",
      showtan: false,
      tishititle: "",
      tishimessage: "",
    })
  },
  async queren() {
    this.setData({
      showtan: false,
      tishititle: "",
      tishimessage: "",
    })
    if (this.data.types == '移除') {
      app.api.removeFromErrorBook(this.data.questionId).then(() => {
        wx.showToast({
          title: '移除成功',
          icon: 'success'
        });
        this.goToQuestion(1);
      }).catch(err => {
        console.error('移除错题失败:', err);
        wx.showToast({
          title: '移除失败，请重试',
          icon: 'none'
        });
      });
    }
    console.log(this.data.types == '重做科目')
    console.log(222222222222222)
    if (this.data.types == '重做科目') {
      // 用户点击确定，执行重做操作
      await this.redoAnswerCard();

    }


  },

  /**
   * 重做整张答题卡
   */
  async redoAnswerCard() {
    const that = this;
    const app = getApp();

    // 检查是否有答题卡ID
    if (!this.data.answerCardId) {
      wx.showToast({
        title: '答题卡信息不完整',
        icon: 'none'
      });
      return;
    }

    // // 显示加载中
    // wx.showLoading({
    //   title: '正在重置答题卡...',
    //   mask: true
    // });

    // 调用重置答题卡接口
    app.api.resetAnswerCard({
      answerCardId: this.data.answerCardId
    }).then(async res => {
      wx.hideLoading();

      if (res.code === 200) {
        wx.showToast({
          title: '答题卡重置成功',
          icon: 'success',
          duration: 1000
        });
        await this.requestData()
        this.goToQuestion(1)
        // 重新加载答题卡数据
        // setTimeout(() => {
        //   that.loadAnswerCardDetail();
        // }, 2000);
      } else {
        wx.showToast({
          title: res.message || '重置失败，请重试',
          icon: 'none'
        });
      }
    }).catch(error => {
      wx.hideLoading();
      console.error('重置答题卡失败:', error);
      wx.showToast({
        title: '网络错误，请检查网络连接',
        icon: 'none'
      });
    });
  },
  /**
 * 显示重做确认对话框
 */
  showRedoConfirm: function () {
    const that = this;
    this.setData({
      types: "重做科目",
      showtan: true,
      tishititle: "重做科目",
      tishimessage: "确定要重新做该科目?",
    })

    // wx.showModal({
    //   title: '确认重做',
    //   content: '确定要重做整张答题卡吗？这将清空所有答题记录，重新开始答题。',
    //   confirmText: '确定重做',
    //   cancelText: '取消',
    //   success: function (res) {
    //     if (res.confirm) {
    //       // 用户点击确定，执行重做操作
    //       that.redoAnswerCard();
    //     }
    //   }
    // });
  },
  /**
   * 重做功能
   */
  redoQuestion: function () {
    console.log(333333333333333)
    let indexs = 0
    this.data.allQuestions.map((item, index) => {
      if (item.questionid == this.data.questionId) {
        indexs = index
      }
    })
    let indexs2 = 0
    this.data.questions.map((item, index) => {
      if (item.questionid == this.data.questionId) {
        indexs2 = index
      }
    })
    // if (this.data.allQuestions[indexs].theoptions) {
    //   this.data.allQuestions[indexs].theoptions.map(item => {
    //     item.theoptions = item.theoptions.map(ziitem => {
    //       ziitem.user_answer = false
    //       return ziitem
    //     })
    //     return item
    //   })
    // }
    // console.log(indexs2)
    this.setData({
      [`allQuestions[${indexs}].user_answer`]: "",
      [`allQuestions[${indexs}].selectmore`]: false,
      [`questions[${indexs2}].user_answer`]: "",
      [`questions[${indexs2}].selectmore`]: false
    })


    if (this.data.allQuestions[indexs].theoptions) {
      this.setData({
        [`allQuestions[${indexs}].theoptions`]: this.data.allQuestions[indexs].theoptions.map(item => {
          // consol.log(item)
          // item.theoptions = item.theoptions.map(ziitem => {
          item.selectmore = false
          // })
          return item
        }),
      })
      setTimeout(() => {
        this.setData({
          [`questions[${indexs2}].theoptions`]: this.data.allQuestions[indexs].theoptions,
        })
        console.log(this.data.questions[indexs2].theoptions)
      }, 10);
    }

    console.log(this.data.questions)
  },
  /**
   * 处理纠错提交
   */
  handleJiucuoSubmit: function (e) {
    // 从组件传递的数据中获取内容和错误类型
    const content = e.detail && e.detail.content ? e.detail.content : this.data.feedbackContent;
    const errorType = e.detail && e.detail.errorType ? e.detail.errorType : '其他';

    if (!content.trim()) {
      wx.showToast({
        title: '请输入纠错内容',
        icon: 'none'
      });
      return;
    }

    const that = this;
    app.api.submitFeedback({
      questionId: this.data.questionId,
      content: content,
      error_type: errorType  // API期望下划线命名
    }).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });

      // 清空内容并关闭弹窗
      that.setData({
        feedbackContent: '',
        showJiucuoModal: false
      });
    }).catch(err => {
      console.error('提交纠错失败:', err);
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
    });



  },
  // 打开纠错弹窗
  openJiucuoModal: function () {
    this.setData({
      showJiucuoModal: true
    });
  },

  // 关闭纠错弹窗
  closeJiucuoModal: function () {
    this.setData({
      showJiucuoModal: false
    });
  },

  selectAnswer(e) {
    const { questionId, answerId } = e.currentTarget.dataset;
    console.log("选择的问题ID:", questionId, "选择的答案ID:", answerId);

    // 可以更新到 allQuestions 中
    const list = this.data.allQuestions.map((item) => {
      if (item.id === questionId) {
        item.selectedAnswerId = answerId;
      }
      return item;
    });

    const list2 = this.data.questions.map((item) => {
      if (item.id == questionId) {
        item.selectedAnswerId = answerId;
      }

      return item;
    });

    this.setData({
      allQuestions: list,
      questions: list2,
    });
  },

  /**
   * 点击问题序号
   * @param {*} e
   */
  onQuestionItemClick(e) {
    const { sortNum } = e.currentTarget.dataset;
    console.log("点击的问题序号:", sortNum);
    this.goToQuestion(sortNum);
  },

  fixSortNum(sortNum) {
    // 处理超出范围的情况
    if (sortNum > this.data.totalQuestions) {
      // 超出范围，从1开始
      sortNum = 1;
    } else if (sortNum < 1) {
      // 超出范围，从最后1开始
      sortNum = this.data.totalQuestions;
    }

    return sortNum;
  },
  goti(valueid) {
    this.data.allQuestions.map((item, index) => {
      if (item.sort == valueid.detail.questionId) {
        this.goToQuestion(index + 1)
      }
    })
  },
  /**
   * 跳转指定问题
   * @param {*} sortNum 问题序号
   */
  goToQuestion(sortNum) {
    // size 固定 5
    sortNum = this.fixSortNum(sortNum);

    // 更新当前显示的问题序号
    this.setData({
      currentShowSortNum: sortNum,
      questionId: this.data.allQuestions[sortNum - 1].questionid
    });

    // 转成索引
    const index = sortNum - 1;

    // 计算范围
    let startIndex = index - 2;
    let endIndex = index + 2;

    // 处理边界情况, 保证可以无限循环
    if (startIndex < 0) {
      startIndex = this.data.totalQuestions + startIndex;
    }
    if (endIndex >= this.data.totalQuestions) {
      endIndex = endIndex - this.data.totalQuestions;
    }

    // 计算并截取循环区间内的5个问题，支持跨越首尾的情况
    let questions = [];
    if (startIndex <= endIndex) {
      // 正常顺序区间
      questions = this.data.allQuestions.slice(startIndex, endIndex + 1);
    } else {
      // 跨越首尾的情况，如 18 -> 2
      questions = [
        ...this.data.allQuestions.slice(startIndex),
        ...this.data.allQuestions.slice(0, endIndex + 1),
      ];
    }

    // 确保每个问题都有必要的字段
    questions = questions.map(question => {
      const processedQuestion = {
        ...question,
        selectedOption: question.selectedOption !== undefined ? question.selectedOption : null,
        selectedOptions: question.selectedOptions !== undefined ? question.selectedOptions : [],
        isAnswered: question.isAnswered !== undefined ? question.isAnswered : false,
        isCorrect: question.isCorrect !== undefined ? question.isCorrect : false,
        userAnswer: question.userAnswer !== undefined ? question.userAnswer : null,
        selectedClass: question.selectedClass !== undefined ? question.selectedClass : []
      };
      return processedQuestion;
    });

    // 索引在中间，固定 2
    this.setData({
      currentIndex: 2,
      questions,
    });
    setTimeout(() => {
      this.processQuestions()
    }, 5);
    // this.goToQuestionCallback(sortNum);
  },

  /**
   * 跳转指定问题后回调
   * @param {*} sortNum
   */
  goToQuestionCallback(sortNum) {
    // 加载评论
  },
});
